#include "TimerFd.h"
#include <unistd.h>
#include <poll.h>
#include <sys/timerfd.h>

TimerFd::TimerFd(int initSec, int peridocSec, TimerFdCallback &&cb)
: _timerfd(createTimerFd())
, _initSec(initSec)
, _peridocSec(peridocSec)
, _isStarted(false)
, _cb(std::move(cb))
{

}

TimerFd::~TimerFd()
{
    setTimerFd(0, 0);
    close(_timerfd);
}

void TimerFd::start()
{
    struct pollfd pfd;
    pfd.fd = _timerfd;
    pfd.events = POLLIN;

    //设置定时器
    setTimerFd(_initSec, _peridocSec);

    _isStarted = true;
    while(_isStarted)
    {
        int nready = poll(&pfd, 1, 5000);
        cout << "nready = " << nready << endl;
        if(-1 == nready && errno == EINTR)
        {
            continue;
        }
        else if(-1 == nready)
        {
            perror("poll -1 == nready");
            return;
        }
        else if(0 == nready)
        {
            cout << ">>poll time_out" << endl;
        }
        else
        {
            if(pfd.revents & POLLIN)
            {
                handleRead();//执行read操作
                if(_cb)
                {
                    _cb();//执行回调函数
                }
            }
        }
    }
}
void TimerFd::stop()
{
    _isStarted = false;
    setTimerFd(0, 0);
}

void TimerFd::handleRead()
{
    uint64_t one;
    ssize_t ret = read(_timerfd, &one, sizeof(one));
    if(ret != sizeof(one))
    {
        perror("read");
        return;
    }
}
int TimerFd::createTimerFd()
{
    int fd = timerfd_create(CLOCK_REALTIME, 0);
    if(fd < 0)
    {
        perror("timerfd_create");
        return fd;
    }
    return fd;
}

void TimerFd::setTimerFd(int initSec, int peridocSec)
{
    struct itimerspec value;
    //初始时间
    value.it_value.tv_sec = initSec;
    value.it_value.tv_nsec = 0;

    //周期时间
    value.it_interval.tv_sec = peridocSec;
    value.it_interval.tv_nsec = 0;

    int ret = timerfd_settime(_timerfd, 0, &value, nullptr);
    if(ret < 0)
    {
        perror("timerfd_settime");
    }
}
